package cn.cloud9.activiti7.processvariable;

import cn.cloud9.activiti7.var.Evection;
import org.activiti.engine.*;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.junit.Before;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * 局部变量在任务结束后销毁，不可复用
 * @author OnCloud9
 * @description
 * @project activiti7
 * @date 2022年08月20日 下午 11:49
 */
public class ProcessLocalVariable {

    private ProcessEngine processEngine;
    private RepositoryService repositoryService;
    private RuntimeService runtimeService;
    private TaskService taskService;
    private HistoryService historyService;
    private ManagementService managementService;

    /**
     * 初始化预备资源
     */
    @Before
    public void loadingResource() {
        processEngine = ProcessEngines.getDefaultProcessEngine();
        repositoryService = processEngine.getRepositoryService();
        runtimeService = processEngine.getRuntimeService();
        taskService = processEngine.getTaskService();
        historyService = processEngine.getHistoryService();
        managementService = processEngine.getManagementService();
    }

    /**
     * 在任务执行的时候变化变量
     */
    @Test
    public void setProcessVariableInCompleteTask() {
        final TaskQuery taskQuery = taskService.createTaskQuery();
        final Task task = taskQuery
                .processDefinitionKey("evection-global-var")
                .processInstanceId("47501")
                .taskAssignee("李四")
                .singleResult();

        final Evection evection = new Evection();
        evection.setDays(2D);
        final Map<String, Object> processVarMap = new HashMap<>();
        processVarMap.put("evection", evection);

        // 配置本地变量
        taskService.setVariableLocal(task.getId(), "evection", evection);
        taskService.setVariablesLocal(task.getId(), processVarMap);

        taskService.complete(task.getId());
    }

    /**
     * 在流程实例下具体某个任务中配置变量
     */
    @Test
    public void setProcessVariableInTask() {
        final Evection evection = new Evection();
        evection.setDays(2D);
        final Map<String, Object> processVarMap = new HashMap<>();
        processVarMap.put("evection", evection);

        String taskId = "当前任务执行ID";

        // 在运行服务对象中指定具体任务的变量, 设置单个值和多个值
        taskService.setVariableLocal(taskId, "evection", evection);
        taskService.setVariablesLocal(taskId, processVarMap);
    }
}
